package com.foreveross.fetl.queue;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.foreveross.fetl.core.domain.single.SinglePlaneInfoEntity;
import com.foreveross.fetl.core.domain.task.SourceEntity;
import com.foreveross.fetl.core.domain.task.UserCareLineEntity;
import com.foreveross.fetl.queue.util.LogMessageUtils;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.util.StringUtils;
@Component
public class LineDayPreprocess {
	private static Logger log = Logger.getLogger("lineDay");
	private int tasksNumber;//任务数 多少条rowkey
	
	private int failuresNumber;//失败数
	
	private int insertNumber; //插入条数 
	
	private long excuteStartTime;
	
	private String taskTime=null;
	
	/**
	 * 定时方法
	 */
	public void execute() {
		rollBackNumber();
		final Calendar c = Calendar.getInstance();
		c.add(Calendar.HOUR_OF_DAY, -1);
		taskTime=DateUtils.format(c.getTime(), "yyyy-MM-dd HH");
		process(c.getTime());
		LogMessageUtils.build("航线最低价", this.getClass().getSimpleName(), 2, null, 
				failuresNumber, tasksNumber, insertNumber, taskTime, excuteStartTime);
	}
	
	/**
	 * 手动方法
	 * @param start
	 * @param time
	 */
	public void manualExecute( String start,String time){
		this.rollBackNumber();
		try {
			List<String> timeList = Arrays.asList(time.split(";"));
			
			taskTime = start + " " +time;
			for (String s : timeList) {
				String str =start;
				str += s;
				Date startTime = DateUtils.parse(str, "yyyyMMddHH");
				this.process(startTime);
			}
		} catch (Exception e) {
			LogMessageUtils.build("航线最低价", this.getClass().getSimpleName(), 3, StringUtils.getStackTrace(e), failuresNumber, tasksNumber, 
					insertNumber, taskTime, excuteStartTime);
			log.error(StringUtils.getStackTrace(e));
		}
		LogMessageUtils.build("航线最低价", this.getClass().getSimpleName(), 2, null, 
				failuresNumber, tasksNumber, insertNumber, taskTime, excuteStartTime);
	}
	
	/**
	 * 重置
	 */
	public void  rollBackNumber(){
		tasksNumber=0;
		failuresNumber=0;
		insertNumber=0;
		excuteStartTime = System.currentTimeMillis();
		LogMessageUtils.create("航线最低价", this.getClass().getSimpleName());
	}
	
	
	private void process(Date date) {
		SourceEntity sourceEntity = new SourceEntity();
		List<SourceEntity> listSource =sourceEntity.findAll();
		UserCareLineEntity userCareLineEntity =new UserCareLineEntity();
		List<UserCareLineEntity> lines =userCareLineEntity.findUserCareLines();//目前处理用户已关注的航线
		SinglePlaneInfoEntity singlePlaneInfo =new SinglePlaneInfoEntity();
		List<SinglePlaneInfoEntity> oldLineDayList=null;
		List<SinglePlaneInfoEntity> listSingel=null;
		Map<String,SinglePlaneInfoEntity> map =new HashMap<String,SinglePlaneInfoEntity>();
		for(SourceEntity source:listSource){
			 try {
				for(UserCareLineEntity line:lines){
					tasksNumber++;
					//该航线的所实时数据  DateUtils.format(date, "yyyyMMddHH")
					listSingel=singlePlaneInfo.findPlaneInfoProperty(source.getHbaseKey(), null, line.getDepartCityCode(), line.getArrivalCityCode(), null, null,null);
					oldLineDayList=singlePlaneInfo.findFromPlaneDay(source.getHbaseKey(), line.getDepartCityCode(), line.getArrivalCityCode(), null);//航线已存在的数据
					if(null==listSingel || listSingel.isEmpty()) 
						continue;
					map.clear();
					for(SinglePlaneInfoEntity entity:listSingel){//获得该日期的最低价航班
						if(null==map.get(entity.getFlightDate())){
							map.put(entity.getFlightDate(), entity);
						}else{
							if(map.get(entity.getFlightDate()).getTotalLowestPrice()>entity.getTotalLowestPrice()){
								map.put(entity.getFlightDate(), entity);
							}
						}
					}
					this.saveLineDay(map,oldLineDayList);
				}
			} catch (SQLException e) {
				e.printStackTrace();
				failuresNumber++;
			}
		}
		
	}


	private void saveLineDay(Map<String, SinglePlaneInfoEntity> map,
			List<SinglePlaneInfoEntity> oldLineDayList) {
		SinglePlaneInfoEntity singlePlaneInfo =new SinglePlaneInfoEntity();
		if(null!=map && map.size()>0){
			try {
				for(String key:map.keySet()){
					SinglePlaneInfoEntity oldEntity=this.getOldEntity(map.get(key),oldLineDayList);
					if(null!=oldEntity){
						if(map.get(key).getTotalLowestPrice()<=oldEntity.getTotalLowestPrice()){
							singlePlaneInfo.deleteFormPlaneDay(oldEntity);//新的比之前的价格低 先删除旧的再保存新的 
							singlePlaneInfo.creatToPlaneDay(map.get(key));
							insertNumber++;
						}
					}else{
						singlePlaneInfo.creatToPlaneDay(map.get(key));
						insertNumber++;
					}
				}
			} catch (SQLException e) {
				e.printStackTrace();
				failuresNumber++;
			}
		}
		
	}


	private SinglePlaneInfoEntity getOldEntity(
			SinglePlaneInfoEntity newEntity,
			List<SinglePlaneInfoEntity> oldLineDayList) {
		if(null==oldLineDayList || oldLineDayList.isEmpty()) 
			return null;
		for(SinglePlaneInfoEntity oldEntity:oldLineDayList){
			if(newEntity.getFlightDate().equals(oldEntity.getFlightDate()) && 
			   newEntity.getFromCity().equals(oldEntity.getFromCity())	&&
			   newEntity.getToCity().equals(oldEntity.getToCity())){
				return oldEntity;
			}
		}
		return null;
	}

}
